//
//  API.swift
//  pgy
//
//  Created by vsccw on 2018/12/29.
//  Copyright © 2018 vsccw.com. All rights reserved.
//

import Moya
import RxSwift
import Alamofire

struct APIConfig {
  struct iOS {
    static let apiKey = "272353093476aeb8e1578d1ef4dac12f"
    static let uKey = "c71663c7955059810040630af58264ea"
  }
}

class API {
  
  enum Account {
    case iOS
  }
  
  static let shared = API()
  
  let provider = MoyaProvider<PGYAPI>()
  
  func start() -> Observable<[AppInfo]> {
    return provider.rx.request(.listMyPublish(1, .iOS))
      .asObservable()
      .map(ListMyPublish.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: false)
      .debug()
      .asObservable()
      .map({ $0.data?.apps ?? [] })
      .catchErrorJustReturn([])
  }
}


extension API.Account {
  var apiKey: String {
    switch self {
    case .iOS:
      return APIConfig.iOS.apiKey
    }
  }
  
  var uKey: String {
    switch self {
    case .iOS:
      return APIConfig.iOS.uKey
    }
  }
}



enum PGYAPI {
  case listMyPublish(Int, API.Account)
  
}

extension PGYAPI: TargetType {
  var baseURL: URL {
    return URL(string: "http://www.pgyer.com")!
  }
  
  var path: String {
    switch self {
    case .listMyPublish:
      return "/apiv1/user/listMyPublished"
    }
  }
  
  var method: Moya.Method {
    switch self {
    case .listMyPublish:
      return .post
    }
  }
  
  var sampleData: Data {
    return Data()
  }
  
  var task: Task {
    switch self {
    case .listMyPublish(let page, let account):
      let parameters: Parameters = ["uKey": account.uKey, "_api_key": account.apiKey, "page": page]
      return Task.requestParameters(parameters: parameters, encoding: URLEncoding.default)
    }
  }
  
  var headers: [String : String]? {
    return ["Content-Type": "application/x-www-form-urlencoded"]
  }
  
  
}
